<template>
	<div id="lineAndPoly">
		<a-input-search
			v-model:value="searchValue"
			placeholder="搜索"
			style="width: 200px; opacity: 0.8"
		/>
		<a-tree
			v-model:checkedKeys="checkedKeys"
			:show-line="showLine"
			:show-icon="showIcon"
			:defaultExpandAll="true"
			:tree-data="gData"
			checkable
			:expanded-keys="expandedKeys"
			:auto-expand-parent="autoExpandParent"
			@select="onSelect"
			@check="onCheck"
			@expand="onExpand"
		>
			<template #title="{ title }">
				<span v-if="title.indexOf(searchValue) > -1">
					{{ title.substring(0, title.indexOf(searchValue)) }}
					<span style="color: #f50">{{ searchValue }}</span>
					{{ title.substring(title.indexOf(searchValue) + searchValue.length) }}
				</span>
				<span v-else>{{ title }}</span>
			</template>
			<template #switcherIcon="{ dataRef, defaultIcon }">
				<FileSyncOutlined v-if="dataRef.key == '0-01'" />
				<component :is="defaultIcon" v-else />
			</template>
		</a-tree>
	</div>
</template>
<script setup>
import {
	ref,
	reactive,
	defineProps,
	watch,
	onMounted,
	watchEffect,
	nextTick,
} from 'vue';
import { ningdongborder } from '@/views/mapBorder';
import { apiGet } from '@shared/untils/common.js';
import dayjs from 'dayjs';
import { saveItem, getItems, getItemById } from '@/db';
const showLine = ref(true);
const showIcon = ref(true);
let rootPath = '/'
rootPath = '/webgis'

const props = defineProps({
	overlays: Object,
	updateOverlays: Function,
	updateList: String,
	updateAmenuTopList: Function,
	catMap: Object,
});
// watch(() => props.overlays,async (newValue) => {
//     props.overlays.value = newValue
// });
watch(
	() => props.updateList,
	(newValue) => {
		updateTreeList();
	}
);

const expandedKeys = ref(['tree3001', 'tree3002', 'tree3003']);
const checkedKeys = ref([]);
const searchValue = ref('');
const autoExpandParent = ref(true);

const formDataByDBList = ref(null);
const treeList = ref([
	{
		title: '行政区域管理',
		key: 'tree3002',
		children: [
			{
				title: '行政区域围栏',
				key: 'parentFence1',
				maptype: 'Overlay.Polygon',
				children: [],
			},
		],
	},
	{
		title: '卡口区域管理',
		key: 'tree3003',
		children: [
			{
				title: '多边形围栏',
				key: 'parentFence2',
				maptype: 'Overlay.Rectangle',
				children: [],
			},
		],
	},
	{
		title: '线路管理',
		key: 'tree3001',
		children: [
			{
				title: '线路预警围栏',
				key: 'parentFence3',
				maptype: 'Overlay.Polyline',
				children: [],
			},
		],
	},
]);

const dataList = [];
const generateList = (data) => {
	for (let i = 0; i < data.length; i++) {
		const node = data[i];
		const key = node.key;
		dataList.push({
			key,
			title: node.title,
		});
		if (node.children) {
			generateList(node.children);
		}
	}
};

const getParentKey = (key, tree) => {
	let parentKey;
	for (let i = 0; i < tree.length; i++) {
		const node = tree[i];
		if (node.children) {
			if (node.children.some((item) => item.key === key)) {
				parentKey = node.key;
			} else if (getParentKey(key, node.children)) {
				parentKey = getParentKey(key, node.children);
			}
		}
	}
	return parentKey;
};
const gData = ref(treeList.value);
const onExpand = (keys) => {
	expandedKeys.value = keys;
	autoExpandParent.value = false;
};
watch(searchValue, (value) => {
	const expanded = dataList
		.map((item) => {
			if (item.title.indexOf(value) > -1) {
				return getParentKey(item.key, gData.value);
			}
			return null;
		})
		.filter((item, i, self) => item && self.indexOf(item) === i);
	expandedKeys.value = expanded;
	searchValue.value = value;
	autoExpandParent.value = true;
});

const updateTreeList = async () => {
	formDataByDBList.value = await getItems();
	// formDataByDBList.value.push(...await getItems('polygon'))
	// formDataByDBList.value.push(...await getItems('govLine'))

	let responseLine = 'getFenceList';
	if (__prd__ || __dev__) {
		responseLine = await apiGet(rootPath + 'applet/getLineList.action');
		if (responseLine?.data?.success && responseLine.data.data) {
			responseLine.data.data.forEach((item) => {
				item.areaType = 'govLine';
				item.userName = '管理员';
				item.id = 'line_' + item.id;
			});
			formDataByDBList.value.push(...responseLine.data.data);
		}
	}

	let responseFence = 'getFenceList';
	if (__prd__ || __dev__) {
		responseFence = await apiGet(rootPath + 'applet/getFenceList.action');
		if (responseFence?.data?.success && responseFence.data.data) {
			responseFence.data.data.forEach((item) => {
				item.areaType = 'polygon';
				item.userName = '管理员';
				item['isAPIPolygon'] = true;
			});
			formDataByDBList.value.push(...responseFence.data.data);
		}
	}

	setTimeout(() => {
		treeList.value[1]['children'][0]['children'] = formDataByDBList.value
			.filter((item) => item.areaType == 'polygon')
			.map((item) => {
				let data = {
					title: item.name,
					key: item.key ? item.key : item.id,
					maptype: 'Overlay.Polygon',
				};
				data.key = data.key + '';
				if (item.isAPIPolygon) data.isAPIPolygon = item.isAPIPolygon;
				return data;
			});

		treeList.value[0]['children'][0]['children'] = formDataByDBList.value
			.filter((item) => item.areaType == 'govArea') // 过滤掉不符合条件的项
			.map((item) => {
				let data = {
					title: item.name,
					key: item.key ? item.key : item.id,
					disableCheckbox: item.key == 7789 ? false : false,
					maptype: 'Overlay.Rectangle',
				};
				data.key = data.key + '';
				return data;
			});

		treeList.value[2]['children'][0]['children'] = formDataByDBList.value
			.filter((item) => item.areaType == 'govLine')
			.map((item) => {
				let data = {
					title: item.name,
					key: item.key ? item.key : item.id,
					disableCheckbox: item.key == 7789 ? false : false,
					maptype: 'Overlay.Polyline',
				};
				data.key = data.key + '';
				return data;
			});

		// checkedKeys.value.push('7788')
		checkedKeys.value.push('7789');
		// checkedKeys.value.push('8888')
		// checkedKeys.value.push('8889')

		generateList(treeList.value);
	}, 100);
};

onMounted(async () => {
	formDataByDBList.value = await getItems();

	addPolygon(ningdongborder, '', 7789, 'govArea');

	nextTick(() => {
		setTimeout(() => {
			updateTreeList();
			props.updateAmenuTopList();
		}, 500);
	});
});
// 获取getItem 数据后对数据处理成ant树数据格式

const onSelect = (selectedKeys, info) => {
	if (info.selected) {
		if (props.overlays[info.node.key]) {
			// 上、下、左、右
			let paddings = [160, 200, 400, 400].map((val) => (val *= 0.9));
			props.catMap.setFitView([props.overlays[info.node.key]], false, paddings);
		}
	}
};

// 根据选中节点显示或隐藏覆盖物
// 当前添加覆盖物的列表中如果它们的key和复选框数据key一致, 进行显示隐藏
const onCheck = (checkedKeys, checked) => {
	let checkedItem = checked.node
	if (checkedItem.children) {
		checkedItem = checked.node.children
	}
	if (checkedItem?.[0]?.children) {
		checkedItem = checkedItem[0].children
	}
	console.info(checkedItem, 'checkedItemcheckedItem')
	if (checked.checked) {
		let showOverlays = []
		// 组选择
		if (checkedItem.length) {
			checkedItem.forEach(item => {
				if (!props.overlays[item['key']]) {
					addMapMarker(item)
				} else {
					props.overlays[item['key']].show()
				}
			})
			checkedItem.forEach(item => {
				if (props.overlays[item.key]) {
					showOverlays.push(props.overlays[item.key])
				}
			})
		}
		// 单选
		else {
			if (!props.overlays[checkedItem['key']]) {
				addMapMarker(checkedItem)
			} else {
				props.overlays[checkedItem['key']].show()
			}
			showOverlays.push(props.overlays[checkedItem.key])
		}
		if (showOverlays.length > 0) {
			let paddings = [160, 200, 400, 400].map((val) => (val *= 0.9));
			props.catMap.setFitView(showOverlays, false, paddings);
		}
		function addMapMarker(item) {
			let currentItemInfo = formDataByDBList.value.filter((it) => it.id == item['key'])[0];
			let lnglats = currentItemInfo.points.split(';');
			let path = lnglats.map((lnglat) => {
				return lnglat.split(',');
			});
			if (item['maptype'] === 'Overlay.Polygon' || item['maptype'] === 'Overlay.Rectangle') {
				addPolygon(
					path,
					currentItemInfo['name'],
					item.key,
					'',
					item.isAPIPolygon ?? false
				);
			}
			if (item['maptype'] === 'Overlay.Polyline') {
				addPolyline(path, currentItemInfo['name'], item.key);
			}
		}
	} else {
		// marker隐藏操作
		// 组选择
		if (checkedItem.length) {
			checkedItem.forEach(item => {
				if (props.overlays[item['key']]) {
					props.overlays[item['key']].hide()
				}
			})
		}
		// 单选
		else {
			if (props.overlays[checkedItem['key']]) {
				props.overlays[checkedItem['key']].hide()
			}
		}
	}
};

let zIndexAddNum = 1;

function addPolyline(path, where = '', key) {
	var polyline = new AMap.Polyline({
		path: path,
		isOutline: true,
		outlineColor: 'transparent',
		borderWeight: 3,
		strokeColor: '#e52b1d',
		strokeOpacity: 1,
		strokeWeight: 3,
		// 折线样式还支持 'dashed'
		strokeStyle: 'solid',
		// strokeStyle是dashed时有效
		strokeDasharray: [5, 5],
		lineJoin: 'round',
		lineCap: 'round',
		extData: {
			weilan: true,
		},
	});
	var text = new AMap.Text({
		text: where, //标记显示的文本内容
		anchor: 'center', //设置文本标记锚点位置
		draggable: true, //是否可拖拽
		cursor: 'pointer', //指定鼠标悬停时的鼠标样式。
		angle: 0, //点标记的旋转角度
		style: {
			//设置文本样式，Object 同 css 样式表
			padding: '0.15rem .35rem',
			'margin-bottom': '1rem',
			'border-radius': '0.25rem',
			'background-color': 'rgb(21 40 91 / 58%)',
			'border-width': '0px',
			'text-align': 'center',
			'font-size': '12px',
		},

		position: [path[0][0], path[0][1]], //点标记在地图上显示的位置
	});
	polyline.on('mouseover', () => {
		text.setMap(props.catMap);
	});
	polyline.on('mouseout', () => {
		props.catMap.remove(text);
	});
	props.catMap.add(polyline);
	props.overlays[key] = polyline;
	DBAddItem(key, key, path, 'govLine');
	// props.catMap.setFitView();
}

function addPolygon(
	path,
	where = '',
	key,
	areaType = '',
	isAPIPolygon = false
) {
	// 使用map和forEach来遍历并修改每个坐标
	path = path.map((coordinates) => {
		return coordinates.map((coordinate) =>
			parseFloat((coordinate * 1).toFixed(6))
		);
	});
	let layData = {
		path: path,
		fillColor: '#00b0ff',
		strokeOpacity: 1,
		fillOpacity: 0.5,
		strokeColor: '#80d8ff',
		strokeWeight: 1,
		strokeStyle: 'dashed',
		strokeDasharray: [5, 5],
		zIndex: 50 + zIndexAddNum,
	};
	if (key == 7789) {
		layData = {
			strokeColor: '#04385f',
			strokeWeight: 2,
			fillOpacity: 0.3,
			fillColor: '#1791fc',
			zIndex: 49,
			bubble: true,
		};
		layData.path = path;
	}
	layData.extData = {
		weilan: true,
	};

	if (isAPIPolygon) {
		layData.extData = {
			APIWeilan: true,
		};
	}

	let polygon;
	if (!props.overlays[key]) {
		polygon = new AMap.Polygon(layData);
	} else {
		polygon = props.overlays[key];
	}

	zIndexAddNum++;
	//   text.setMap(catMap); //将文本标记设置到地图上
	let bounds = polygon.getBounds();
	let lng = bounds['northEast']
		? bounds['northEast'].lng
		: bounds['northeast']
		? bounds['northeast'].lng
		: '';
	let lat = bounds['northEast']
		? bounds['northEast'].lat
		: bounds['northeast']
		? bounds['northeast'].lat
		: '';
	var text = new AMap.Text({
		text: where, //标记显示的文本内容
		anchor: 'center', //设置文本标记锚点位置
		draggable: true, //是否可拖拽
		cursor: 'pointer', //指定鼠标悬停时的鼠标样式。
		angle: 0, //点标记的旋转角度
		style: {
			//设置文本样式，Object 同 css 样式表
			padding: '0.15rem .35rem',
			'margin-bottom': '1rem',
			'border-radius': '0.25rem',
			'background-color': 'rgb(21 40 91 / 58%)',
			'border-width': '0px',
			'text-align': 'center',
			'font-size': '12px',
		},

		position: [lng, lat], //点标记在地图上显示的位置
	});

	if (key != 7789) {
		polygon.on('mouseover', () => {
			text.setMap(props.catMap);
			polygon.setOptions({
				fillOpacity: 0.7,
				fillColor: '80d8ff',
			});
		});
		polygon.on('mouseout', () => {
			props.catMap.remove(text);
			polygon.setOptions({
				fillOpacity: 0.5,
				fillColor: '00b0ff',
			});
		});
	}
	if (!props.overlays[key]) {
		props.overlays[key] = polygon;
		props.catMap.add(polygon);
		let areaName = key;
		if (key == 7789) {
			areaName = '宁东镇';
		}
		if (!isAPIPolygon) {
			if (areaType) {
				DBAddItem(areaName, key, path, areaType);
			}
		}
	} else {
		polygon.show();
	}
}

async function DBAddItem(name, key, path, areaType) {
	if (Array.isArray(path)) {
		path = path.join(';');
	}
	let FormData = {
		name,
		key,
		id: key,
		userName: '管理员',
		byShare: true,
		byDependency: true,
		bymanor: true,
		byTime: true,
		limitSpeed: true,
		originGpsCoord: true,
		areaType,
		maxSpeed: '90.0',
		startDate: '',
		endDate: '',
		epidemicRisk: '低风险',
		delay: 10,
		glv: 20,
		date: [dayjs().startOf('month'), dayjs()],
		adname: '',
		txnr: '',
		points: path,
		alarmTypes1s: '',
		alarmTypes2s: '',
		alarmType: '',
		type: '',
		checkedList1: ['进区域报警给驾驶员', '进区域报警给平台'],
		checkedList2: ['进区域报警给驾驶员', '进区域报警给平台'],
		approver: '',
		dateTime: null,
		description: '',
	};

	var formInitData = reactive(FormData);
	let rs = await getItemById(areaType, key);
	if (!rs) {
		await saveItem(areaType, formInitData);
	}
}
</script>
<style>
#lineAndPoly
	.ant-tree-checkbox:not(.ant-tree-checkbox-disabled)
	.ant-tree-checkbox-inner {
	background-color: transparent;
	opacity: 0.65;
}

.ant-tree
	.ant-tree-checkbox:not(.ant-tree-checkbox-disabled)
	.ant-tree-checkbox-inner {
	border-color: #d9d9d98a;
}
.lineAndPoly .ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected,
.ant-tree .ant-tree-checkbox + span.ant-tree-node-selected {
	background-color: #3f51b5;
}
</style>
